<!-- 执行工单 -->
<script setup lang="ts">
defineOptions({
  name: "ERC_INSPECT_TASK_FORM_PAGE"
});
import { saveTaskItemResult, submitTask } from "@/api/equip/inspectTask";
import { PxMessage, PxMessageBox } from "px-ui";
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { TAG_CONFIG } from "../config";
import TaskForm from "./TaskForm.vue";
const bacicData = ref<any>({});
const emits = defineEmits(["backMainPage", "refresh"]);
const route = useRoute();
const router = useRouter();
// 执行工单
const taskTormRef = ref<InstanceType<typeof TaskForm>>();
// 返回上一级并刷新数据
const backDetailPage = () => {
  PxMessageBox.confirm(`内容未保存，确认退出执行工单吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  }).then(async () => {
    handleGoBack();
  });
};
const inspectArea = ref();
// 保存
const handleDraft = async ({ hiddenMessage, noBack, index, callback }) => {
  const params = transformFormToSubmit();
  await saveTaskItemResult(params);
  if (!hiddenMessage) {
    PxMessage.success("保存成功");
  }
  if (!noBack) {
    handleGoBack();
  }
  if (callback) {
    await callback();
  }
};
const getTargetData = (data, task, miss, item) => {
  // 巡检内容
  data?.contentDTOList?.forEach(item => {
    item.contentItemDTOList.forEach(contentItem => {
      task.push({ id: contentItem.id, inspectArea: item.inspectArea, result: contentItem.result });
    });
  });
  // 异常上报
  if (data.inspectTaskMissDTO?.checked) {
    let missingPictureList;
    if (data.inspectTaskMissDTO.missingPictureList) {
      missingPictureList = data.inspectTaskMissDTO.missingPictureList.map(item => item.id || item?.response?.data?.id);
    }
    miss.push({ ...item, ...data.inspectTaskMissDTO, missingPictureList });
  }
};
// 转换称后端接收的参数
const transformFormToSubmit = () => {
  const formValue = taskTormRef.value.formValue;
  let inspectTaskItemDTOList = [];
  let inspectTaskMissDTOList = [];
  // 获取全部巡检结果和异常上报
  formValue.forEach((item, index) => {
    const tabItem = bacicData.value.inspectRuleAreaDTOList[index];
    // 遍历环境巡检
    getTargetData(item.envContentDTOlist, inspectTaskItemDTOList, inspectTaskMissDTOList, {
      eqpAreaCode: tabItem.inspectArea,
      inspectArea: tabItem.inspectArea,
      inspectRuleCode: tabItem.ruleCode
    });

    // 遍历设备巡检
    item.eqpContentDTOList?.forEach(eqpItem => {
      getTargetData(eqpItem, inspectTaskItemDTOList, inspectTaskMissDTOList, {
        eqpAreaCode: eqpItem.eqpId,
        inspectArea: tabItem.inspectArea,
        inspectRuleCode: tabItem.ruleCode
      });
    });
  });
  const params = {
    taskCode: formValue[0].taskCode,
    inspectTaskItemDTOList,
    inspectTaskMissDTOList
  };
  return params;
};
// 完成巡检——提交
const handleSubmit = async () => {
  taskTormRef.value.validate(async valid => {
    taskTormRef.value.validated = true;
    if (valid) {
      // 请确认您的巡检结果都已填写完成，点击确定后为您提交巡检结果。
      PxMessageBox.confirm(`请确认您的巡检结果都已填写完成，点击确定后为您提交巡检结果。`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }).then(async () => {
        const params = transformFormToSubmit();
        await submitTask(params);
        // 提交任务
        PxMessage.success("提交成功");
        handleGoBack();
      });
    }
  });
};
const handleGoBack = () => {
  const {
    query: { page }
  } = route;
  if (page) {
    router.push(page as string);
  } else {
    router.go(-1);
  }
};
const signIn = async () => {
  // TODO 临时方案，前端直接点击提示签到成功@产品孙寿磊
  // PxMessage.success("签到成功");
  taskTormRef.value.singIn();
};
// 查看报警记录 /all/alert/business
const showAlert = () => {
  taskTormRef.value.showAlert();
};
</script>
<template>
  <div>
    <div id="task-form-page" class="view-detail-bg">
      <div class="view-task-detail">
        <div class="view-task-title">
          <px-button type="primary" icon="ArrowLeft" @click="backDetailPage">返回</px-button>
          <div class="text-box">
            <px-tooltip effect="dark" :content="bacicData.taskName">
              <px-text class="text" truncated>{{ bacicData.taskName }}</px-text>
            </px-tooltip>
            &nbsp;{{ bacicData.taskCode }}
          </div>
          <div v-show="!!bacicData.taskStatusDesc" class="status">
            <div class="circle" :style="{ backgroundColor: `${TAG_CONFIG[bacicData.taskStatus]?.color}` }" />
            <p :style="{ color: `${TAG_CONFIG[bacicData?.taskStatus]?.color}` }">{{ bacicData.taskStatusDesc }}</p>
          </div>
        </div>
        <div class="btn-group">
          <px-button plain type="primary" @click="showAlert"> 查看报警记录 </px-button>
          <px-button type="primary" @click="signIn"> 一键签到 </px-button>
        </div>
      </div>
      <TaskForm ref="taskTormRef" v-model:bacicData="bacicData" @handleSave="handleDraft" />
      <div class="info-form-btns">
        <px-button @click="backDetailPage">取消</px-button>
        <px-button type="primary" :disabled="[6, 7].includes(bacicData?.taskStatus)" ghost @click="handleSubmit">提交巡检任务</px-button>
        <px-button type="primary" :disabled="[6, 7].includes(bacicData?.taskStatus)" @click="handleDraft">保存当前进度</px-button>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.view-detail-bg {
  min-height: calc(100vh - 195px);
  padding: 0 24px;
  background: #fff;
}
.btn-group {
  flex-shrink: 0;
}
.info-form-btns {
  position: absolute;
  right: 0;
  bottom: 0;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  height: 68px;
  padding-right: 24px;
  background: #fff;
  box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
}

.view-task-detail {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 16px 0;
  overflow: hidden;

  .view-task-title {
    display: flex;
    flex-direction: row;
    align-items: center;
    overflow: hidden;

    .text-box {
      display: flex;
      margin-left: 20px;
      overflow: hidden;
      font-size: 20px;
      font-weight: 600;
      color: rgb(0 0 0 / 90%);
    }

    .text {
      font-size: 20px;
      font-weight: 600;
      color: rgb(0 0 0 / 90%);
    }

    .status {
      display: flex;
      flex-direction: row;
      flex-shrink: 0;
      align-items: center;

      .circle {
        width: 8px;
        height: 8px;
        margin-right: 5px;
        margin-left: 8px;
        border-radius: 50%;
      }
    }
  }
}
</style>
